<?php

namespace App\Modules\Rebate;


use App\Library\Rank\AbstractSingleRank;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Rank extends AbstractSingleRank
{
    protected static $key = "sales_volume:rank:";

    public static function setKey($prefix)
    {
        self::$key = "sales_volume:rank:{$prefix}";
    }

    public static function increaseAll($level, $id, $step = 1)
    {
        self::setKey('monthly:'.$level);
        self::increase($id, $step);

        self::setKey('quarterly:'.$level);
        self::increase($id, $step);

        self::setKey('annual:'.$level);
        self::increase($id, $step);
    }
    public static function flush()
    {
        self::setKey('monthly:1');
        Redis::del(static::$key);
        self::setKey('quarterly:1');
        Redis::del(static::$key);
        self::setKey('annual:1');
        Redis::del(static::$key);
        self::setKey('monthly:2');
        Redis::del(static::$key);
        self::setKey('quarterly:2');
        Redis::del(static::$key);
        self::setKey('annual:2');
        Redis::del(static::$key);
        self::setKey('monthly:3');
        Redis::del(static::$key);
        self::setKey('quarterly:3');
        Redis::del(static::$key);
        self::setKey('annual:3');
        Redis::del(static::$key);
    }
    public static function refresh()
    {
        self::multi(function () {
            static::flush();
            Order::query()
                ->join('users', 'users.id', '=', 'orders.referrer_id')
                ->where('orders.created_at', '>', now()->startOfYear()->toDateString())
                ->whereNotNull('orders.referrer_id')
                ->where('orders.referrer_level', '>', 0)
                ->where('orders.status', Order::STATUS_PAID)
                ->whereRaw('orders.referrer_level = users.level')
                ->select('orders.*')
                ->orderBy('orders.id')
                ->each(function ($item) {
                    if ($item->created_at > now()->startOfMonth()->toDateString()) {
                        self::setKey('monthly:'.$item->referrer_level);
                        self::increase($item->referrer_id, $item->original_price);
                    }

                    if ($item->created_at > now()->startOfQuarter()->toDateString()) {
                        self::setKey('quarterly:'.$item->referrer_level);
                        self::increase($item->referrer_id, $item->original_price);
                    }

                    self::setKey('annual:'.$item->referrer_level);
                    self::increase($item->referrer_id, $item->original_price);
                });
        });
    }
}
